package apig.client.login;

import apig.client.*;
import apig.client.serviface.*;

import com.google.gwt.core.client.*;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.user.client.rpc.*;
import com.google.gwt.user.client.ui.*;

public class LoginEntryPoint implements EntryPoint {

	private Button signinButton;
	private TextBox loginBox;
	private PasswordTextBox passBox;
	private Label signinLabel;

	public void onModuleLoad() {

		RootPanel rlp = RootPanel.get("container");

		VerticalPanel vp = new VerticalPanel();
		signinLabel = new Label("Sign in ...");
		signinButton = new Button("Sign in");
		loginBox = new TextBox();
		passBox = new PasswordTextBox();
		FlexTable ft = new FlexTable();
		ft.setWidget(0, 0, new Label("Login:"));
		ft.setWidget(1, 0, new Label("Passworth:"));
		ft.setWidget(0, 1, loginBox);
		ft.setWidget(1, 1, passBox);

		vp.add(signinLabel);
		vp.add(ft);
		vp.add(signinButton);

		rlp.add(vp);

		signinButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				onTryLogin();
			}
		});
	}

	private void onTryLogin() {
		passBox.setEnabled(false);
		loginBox.setEnabled(false);

		// do the async call to the server
		Stubman.getStubman()
				.getService()
				.doLogin(loginBox.getText(), passBox.getText(),
						new AsyncCallback<Boolean>() {

							@Override
							public void onFailure(Throwable caught) {
								onLoginFail(caught.getMessage());
							}

							@Override
							public void onSuccess(Boolean result) {
								onUserLogged();
							}
						});
	}

	private void onLoginFail(String msg) {
		passBox.setEnabled(true);
		loginBox.setEnabled(true);
		signinLabel.setText(msg);
	}

	private void onUserDataGotten(UserData ud) {
		if (ud == null) {
			return;
		}

		if (ud.role == UserData.ROLE_PROF) {
			// TODO: redirect to prof page
			redirect("http://127.0.0.1:8888/prof.html?gwt.codesvr=127.0.0.1:9997");
		} else if (ud.role == UserData.ROLE_STUD) {
			// TODO: redirect to stud page
			redirect("http://127.0.0.1:8888/stud.html?gwt.codesvr=127.0.0.1:9997");
		}
	}

	public static native void redirect(String url)
	/*-{
		$wnd.location.replace(url);
	}-*/;

	private void onUserLogged() {
		Stubman.getStubman().getService()
				.getUserData(new AsyncCallback<UserData>() {

					@Override
					public void onFailure(Throwable caught) {
						onLoginFail(caught.getMessage());
					}

					@Override
					public void onSuccess(UserData result) {
						onUserDataGotten(result);
					}
				});
	}
}
